<template>
  <div class="mall-container">
    <!-- 顶部导航栏 -->
    <header class="mall-header">
      <div class="header-content">
        <div class="logo-area">
          <div class="mall-logo" @click="goHome">
            <div class="logo-icon">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="48" height="48">
                <!-- 主背景圆 -->
                <circle cx="32" cy="32" r="30" fill="#FFFFFF" stroke="#F06292" stroke-width="2"/>
                
                <!-- 大口红 -->
                <g>
                  <!-- 口红底座 -->
                  <rect x="15" y="20" width="20" height="34" rx="2" fill="#212121"/>
                  <!-- 口红本体 -->
                  <path d="M15,20 h20 v-14 a6,6 0 0,0 -20,0 z" fill="#F50057"/>
                  <!-- 口红顶端 -->
                  <path d="M15,20 h20 v-5 a5,5 0 0,0 -20,0 z" fill="#FF4081"/>
                  <!-- 口红金属环 -->
                  <rect x="17" y="20" width="16" height="3" fill="#FFC107"/>
                </g>
                
                <!-- 腮红圆点 -->
                <circle cx="45" cy="22" r="12" fill="#EC407A" opacity="0.85"/>
                
                <!-- 化妆镜反光 -->
                <ellipse cx="49" cy="18" rx="5" ry="3" fill="white" opacity="0.7" transform="rotate(-20, 49, 18)"/>
              </svg>
            </div>
            <span class="logo-text">美妆商城</span>
          </div>
        </div>
        
        <div class="search-box">
          <div class="search-input-container">
            <i class="el-icon-search search-icon"></i>
            <input 
              type="text" 
              v-model="searchKeyword" 
              placeholder="搜索商品..." 
              class="custom-search-input"
              @keyup.enter="handleSearch"
            />
            <button class="search-button" @click="handleSearch">
              <span>搜索</span>
            </button>
          </div>
        </div>
        
        <div class="user-actions">
          <!-- 通知按钮 -->
          <div class="action-item">
            <el-popover
              placement="bottom"
              :width="300"
              trigger="click"
              popper-class="notification-popover"
            >
              <template #reference>
                <div class="notification-item">
                  <el-badge :value="unreadNotifications.length" :hidden="unreadNotifications.length === 0">
                    <el-icon><Bell /></el-icon>
                  </el-badge>
                  <span>通知</span>
                </div>
              </template>
              <div class="notification-list">
                <div class="notification-header">
                  <h3>系统通知</h3>
                  <el-button v-if="notifications.length > 0" type="text" size="small" @click="markAllAsRead">
                    全部已读
                  </el-button>
                </div>
                <el-empty v-if="notifications.length === 0" description="暂无通知" />
                <el-scrollbar max-height="300px">
                  <div
                    v-for="notification in notifications"
                    :key="notification.notificationId"
                    class="notification-item"
                    :class="{ 'unread': !notification.read }"
                    @click="handleNotificationClick(notification)"
                  >
                    <div class="notification-content">
                      <div class="notification-title">
                        <span>{{ notification.type || '系统通知' }}</span>
                        <span class="notification-time">{{ formatTime(notification.createdAt) }}</span>
                      </div>
                      <div class="notification-body">{{ notification.content }}</div>
                    </div>
                  </div>
                </el-scrollbar>
              </div>
            </el-popover>
          </div>

          <div class="action-item" @click="goToCart">
            <i class="el-icon-shopping-cart-2"></i>
            <span>购物车</span>
            <span class="badge" v-if="cartCount > 0">{{ cartCount }}</span>
          </div>
          <div class="action-item">
            <i class="el-icon-star-on"></i>
            <span>收藏夹</span>
          </div>
          <div class="action-item user-center">
            <el-dropdown trigger="click" @command="handleCommand">
              <span class="user-info">
                <el-avatar size="small" :src="userAvatar" class="user-avatar">
                  <i v-if="!userAvatar" class="el-icon-user"></i>
                </el-avatar>
                <span>{{ username }}</span>
                <i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="orders">
                    <i class="el-icon-s-order"></i> 我的订单
                  </el-dropdown-item>
                  <el-dropdown-item command="profile">
                    <i class="el-icon-user"></i> 个人中心
                  </el-dropdown-item>
                  <el-dropdown-item command="settings">
                    <i class="el-icon-setting"></i> 账户设置
                  </el-dropdown-item>
                  <el-dropdown-item divided command="logout">
                    <i class="el-icon-switch-button"></i> 退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>
    </header>
    
    <!-- 商品分类导航 -->
    <nav class="category-nav">
      <div class="nav-content">
        <div class="category-menu">
          <el-menu mode="horizontal" :default-active="activeCategory" class="category-menu-list" router>
            <el-menu-item index="/user/home">首页</el-menu-item>
            
            <!-- 动态生成分类菜单 -->
            <el-menu-item 
              v-for="category in categories" 
              :key="category.id" 
              :index="`/user/products?category=${category.id}`"
              @click="goToCategory(category.id)"
            >
              {{ category.name }}
            </el-menu-item>
            
            <el-menu-item index="/user/products" @click="goToAllProducts">全部商品</el-menu-item>
          </el-menu>
        </div>
      </div>
    </nav>
    
    <!-- 主要内容区域 - 路由出口 -->
    <main class="mall-content">
      <router-view />
    </main>
    
    <!-- 底部区域 -->
    <footer class="mall-footer">
      <div class="footer-content">
        <div class="footer-section">
          <h3>关于我们</h3>
          <ul>
            <li>品牌故事</li>
            <li>企业责任</li>
            <li>招聘信息</li>
            <li>联系我们</li>
          </ul>
        </div>
        
        <div class="footer-section">
          <h3>购物指南</h3>
          <ul>
            <li>购物流程</li>
            <li>会员介绍</li>
            <li>常见问题</li>
            <li>联系客服</li>
          </ul>
        </div>
        
        <div class="footer-section">
          <h3>配送方式</h3>
          <ul>
            <li>上门自提</li>
            <li>快递配送</li>
            <li>配送范围</li>
            <li>运费说明</li>
          </ul>
        </div>
        
        <div class="footer-section">
          <h3>售后服务</h3>
          <ul>
            <li>退换货政策</li>
            <li>退换货流程</li>
            <li>价格保护</li>
            <li>售后咨询</li>
          </ul>
        </div>
        
        <div class="footer-section contact">
          <h3>联系我们</h3>
          <div class="contact-info">
            <p><i class="el-icon-phone"></i> 400-888-8888</p>
            <p><i class="el-icon-message"></i> service@beauty.com</p>
            <div class="social-icons">
              <i class="el-icon-s-platform"></i>
              <i class="el-icon-s-cooperation"></i>
              <i class="el-icon-s-custom"></i>
            </div>
          </div>
        </div>
      </div>
      
      <div class="copyright">
        <p>© 2025 美妆商城 All Rights Reserved.</p>
      </div>
    </footer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Bell } from '@element-plus/icons-vue';
import { useUserStore } from '../stores/user';
import categoryApi, { ICategoryDto } from '../api/category';
import productApi from '../api/product';
import notificationApi, { INotificationDto } from '../api/notification';

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

// 用户信息
const username = computed(() => userStore.username);
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';
const userAvatar = computed(() => userStore.avatar || defaultAvatar);

// 搜索相关
const searchKeyword = ref('');
const cartCount = ref(0);
const activeCategory = ref('/user/home');

// 通知数据
const notifications = ref<INotificationDto[]>([]);
const unreadNotifications = computed(() => notifications.value.filter(n => !n.read));

// 分类数据
const categories = ref<ICategoryDto[]>([]);
const loading = ref(false);

// 获取通知
const fetchNotifications = async () => {
  try {
    // 使用customerId作为clientId
    const clientId = userStore.customerId;
    if (!clientId) {
      console.error('用户未登录或无法获取客户ID');
      return;
    }
    
    console.log('正在获取通知，clientId:', clientId);
    const result = await notificationApi.getNotificationsByClientId(clientId);
    console.log('获取通知结果:', result);
    
    if (result && result.status === 'OK' && Array.isArray(result.data)) {
      notifications.value = result.data;
      console.log('设置通知数据成功，数量:', notifications.value.length);
    } else {
      console.warn('返回的通知格式不符合预期:', result);
      notifications.value = [];
    }
  } catch (error) {
    console.error('获取通知失败:', error);
    notifications.value = []; // 确保发生错误时通知列表是空数组而不是undefined
  }
};

// 处理通知点击
const handleNotificationClick = async (notification: INotificationDto) => {
  if (!notification.read) {
    try {
      await notificationApi.markNotificationAsRead(notification.notificationId);
      // 更新本地通知状态
      const index = notifications.value.findIndex(n => n.notificationId === notification.notificationId);
      if (index !== -1) {
        notifications.value[index].read = true;
      }
    } catch (error) {
      console.error('标记通知为已读失败:', error);
    }
  }
  
  // 根据通知类型执行不同操作（可以根据业务需求扩展）
  if (notification.type === '订单') {
    router.push('/user/orders');
  } else if (notification.type === '支付') {
    router.push('/user/payment');
  }
};

// 标记所有通知为已读
const markAllAsRead = async () => {
  try {
    // 找出所有未读通知
    const unreadIds = unreadNotifications.value.map(n => n.notificationId);
    
    // 依次标记为已读
    for (const id of unreadIds) {
      await notificationApi.markNotificationAsRead(id);
    }
    
    // 更新本地通知状态
    notifications.value = notifications.value.map(n => ({
      ...n,
      read: true
    }));
    
    ElMessage.success('已将所有通知标记为已读');
  } catch (error) {
    console.error('标记所有通知为已读失败:', error);
    ElMessage.error('操作失败，请稍后重试');
  }
};

// 格式化时间
const formatTime = (timestamp: number) => {
  const date = new Date(timestamp);
  const now = new Date();
  
  // 如果是今天
  if (date.toDateString() === now.toDateString()) {
    return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  }
  
  // 如果是昨天
  const yesterday = new Date();
  yesterday.setDate(yesterday.getDate() - 1);
  if (date.toDateString() === yesterday.toDateString()) {
    return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  }
  
  // 其他日期
  return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

// 获取所有一级分类
const fetchCategories = async () => {
  loading.value = true;
  try {
    const res = await categoryApi.getCategoriesByLevel(1);
    categories.value = res.data || [];
    console.log('获取到的分类:', categories.value);
  } catch (error) {
    console.error('获取分类失败:', error);
    ElMessage.error('获取分类失败，使用默认分类');
    // 使用默认分类
    categories.value = [
      { id: 1, name: '护肤' },
      { id: 2, name: '彩妆' },
      { id: 3, name: '香水' },
      { id: 4, name: '头发护理' }
    ];
  } finally {
    loading.value = false;
  }
};

// 监听路由变化，更新选中的导航项
watch(() => route.path, (newPath) => {
  if (newPath.startsWith('/user/products')) {
    // 如果是商品列表页面，根据参数设置活动分类
    if (route.query.category) {
      activeCategory.value = `/user/products?category=${route.query.category}`;
    } else {
      activeCategory.value = '/user/products';
    }
  } else {
    // 其他页面直接匹配路径
    activeCategory.value = newPath;
  }
}, { immediate: true });

// 跳转到首页
const goHome = () => {
  router.push('/user/home');
};

// 根据分类跳转
const goToCategory = (categoryId: number) => {
  router.push({
    path: '/user/products',
    query: { category: categoryId.toString() }
  });
};

// 前往全部商品页面（不带分类参数）
const goToAllProducts = () => {
  router.push({
    path: '/user/products',
    query: {} // 清除所有查询参数
  });
};

// 搜索处理
const handleSearch = () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词');
    return;
  }
  
  console.log('使用ES搜索商品，关键词:', searchKeyword.value);
  
  // 调用ES搜索接口
  productApi.searchByES(searchKeyword.value)
    .then(response => {
      console.log('ES搜索结果:', response);
      // 搜索成功后跳转到商品列表页面
      router.push({
        path: '/user/products',
        query: { 
          keyword: searchKeyword.value,
          useES: 'true'
        }
      });
    })
    .catch(error => {
      console.error('ES搜索失败:', error);
      ElMessage.error('搜索失败，请稍后重试');
    });
};

// 跳转到购物车
const goToCart = () => {
  router.push('/user/cart');
};

// 处理登出
const handleLogout = () => {
  userStore.logout();
  router.push('/login');
  ElMessage.success('已成功退出登录');
};

// 处理下拉菜单命令
const handleCommand = (command) => {
  if (command === 'logout') {
    handleLogout();
  } else if (command === 'orders') {
    router.push('/user/orders');
  } else if (command === 'profile') {
    router.push('/user/profile');
  } else if (command === 'settings') {
    router.push('/user/settings');
  }
};

onMounted(() => {
  // 获取分类数据
  fetchCategories();
  
  // 验证用户是否登录
  if (!userStore.isLoggedIn) {
    router.push('/login');
    return;
  }
  
  // 验证是否为商家账号
  if (userStore.isMerchant) {
    ElMessage.error('访问被拒绝。正在跳转到商家控制面板。');
    router.push('/merchant/home');
  }
  
  // 获取通知数据
  fetchNotifications();
});
</script>

<style scoped>
.mall-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  width: 100%;
  background-color: #f5f5f5;
  overflow-x: hidden;
}

/* 顶部导航 */
.mall-header {
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  padding: 15px 0;
  position: sticky;
  top: 0;
  z-index: 1000;
  width: 100%;
  border-bottom: 1px solid #f0f0f0;
}

/* 通知样式 */
.notification-item {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.notification-item i {
  margin-right: 5px;
  font-size: 20px;
}

.notification-list {
  padding: 0;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  border-bottom: 1px solid #eee;
}

.notification-header h3 {
  margin: 0;
  font-size: 16px;
}

.notification-list .notification-item {
  padding: 12px;
  border-bottom: 1px solid #f1f1f1;
  cursor: pointer;
  transition: background-color 0.3s;
  display: block;
}

.notification-list .notification-item:hover {
  background-color: #f5f7fa;
}

.notification-list .notification-item.unread {
  background-color: #edf5ff;
}

.notification-title {
  display: flex;
  justify-content: space-between;
  font-weight: bold;
  margin-bottom: 5px;
}

.notification-time {
  font-size: 12px;
  color: #999;
  font-weight: normal;
}

.notification-body {
  font-size: 13px;
  color: #606266;
  line-height: 1.5;
}

.header-content {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 5vw;
}

.mall-logo {
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.mall-logo:hover {
  transform: scale(1.05);
}

.logo-icon {
  margin-right: 12px;
  filter: drop-shadow(0px 3px 5px rgba(0, 0, 0, 0.2));
}

.logo-icon:hover {
  animation: logoWiggle 1s ease;
}

@keyframes logoWiggle {
  0%, 100% { transform: rotate(0deg); }
  25% { transform: rotate(-10deg); }
  50% { transform: rotate(0deg); }
  75% { transform: rotate(10deg); }
}

.logo-text {
  font-size: 24px;
  font-weight: bold;
  background: linear-gradient(135deg, #FF6B98 0%, #FF8DAC 100%);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  letter-spacing: 1px;
  text-shadow: 0px 2px 4px rgba(255, 107, 152, 0.2);
}

.search-box {
  width: 35%;
  min-width: 300px;
  margin: 0 20px;
}

.search-input-container {
  width: 100%;
  position: relative;
  display: flex;
  align-items: center;
  border-radius: 28px;
  background-color: #f6f6f6;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.search-input-container:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background-color: #f8f8f8;
}

.search-input-container:focus-within {
  background-color: #fff;
  box-shadow: 0 4px 15px rgba(255, 107, 152, 0.15);
  border-color: rgba(255, 107, 152, 0.3);
}

.search-icon {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
  font-size: 18px;
  z-index: 1;
  transition: color 0.3s ease;
}

.search-input-container:focus-within .search-icon {
  color: #FF6B98;
}

.custom-search-input {
  width: 100%;
  height: 44px;
  padding: 0 20px 0 45px;
  border: none;
  outline: none;
  font-size: 14px;
  color: #333;
  background-color: transparent;
  transition: all 0.3s ease;
}

.custom-search-input::placeholder {
  color: #999;
  transition: color 0.3s ease;
}

.custom-search-input:focus::placeholder {
  color: #bbb;
}

.search-button {
  height: 44px;
  min-width: 80px;
  padding: 0 20px;
  border: none;
  background-color: #FF6B98;
  color: white;
  font-weight: 500;
  letter-spacing: 1px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  white-space: nowrap;
  font-size: 14px;
}

.search-button:hover {
  background-color: #ff5289;
}

.user-actions {
  display: flex;
  align-items: center;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-left: 20px;
  position: relative;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-item:hover {
  color: #FF6B98;
}

.action-item:hover i {
  color: #FF6B98;
}

.action-item i {
  font-size: 20px;
  color: #606266;
  transition: color 0.3s ease;
}

.action-item span {
  font-size: 12px;
  margin-top: 3px;
  white-space: nowrap;
}

.badge {
  position: absolute;
  top: -5px;
  right: -5px;
  background-color: #FF6B98;
  color: white;
  border-radius: 50%;
  width: 16px;
  height: 16px;
  font-size: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: transform 0.3s ease;
}

.action-item:hover .badge {
  transform: scale(1.1);
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.user-info span {
  transition: color 0.3s ease;
}

.user-info:hover span {
  color: #FF6B98;
}

.user-avatar {
  margin-right: 8px;
  background-color: #f0f2f5;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid transparent;
  transition: all 0.3s ease;
}

.user-center:hover .user-avatar {
  border-color: #FF6B98;
  transform: scale(1.05);
}

.user-center {
  position: relative;
  height: 100%;
}

.el-icon--right {
  margin-left: 5px;
  font-size: 12px;
}

/* 分类导航 */
.category-nav {
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border-top: 1px solid #f0f0f0;
  position: sticky;
  top: 70px;
  z-index: 999;
  width: 100%;
}

.nav-content {
  width: 100%;
  padding: 0 5vw;
}

.category-menu-list {
  border-bottom: none;
  display: flex;
  width: 100%;
  justify-content: center;
}

.el-menu-item {
  font-size: 15px;
  font-weight: 500;
  padding: 0 25px;
  position: relative;
  overflow: hidden;
}

.el-menu-item::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  width: 0;
  height: 2px;
  background-color: #FF6B98;
  transition: all 0.3s ease;
  transform: translateX(-50%);
}

.el-menu-item:hover::after, 
.el-menu-item.is-active::after {
  width: 70%;
}

.el-menu-item.is-active {
  color: #FF6B98;
  font-weight: 600;
}

/* 内容区域 */
.mall-content {
  flex: 1;
  width: 100%;
  padding: 20px 5vw;
  box-sizing: border-box;
}

/* 底部区域 */
.mall-footer {
  background-color: #263238;
  color: #b0bec5;
  padding: 40px 0 0;
  margin-top: 40px;
  width: 100%;
}

.footer-content {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 0 5vw 40px;
}

.footer-section {
  flex: 1;
  min-width: 180px;
  margin-bottom: 20px;
  padding: 0 15px;
}

.footer-section h3 {
  color: #fff;
  margin-bottom: 15px;
  font-size: 16px;
  position: relative;
  padding-bottom: 10px;
}

.footer-section h3:after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 30px;
  height: 2px;
  background-color: #FF6B98;
}

.footer-section ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.footer-section li {
  margin-bottom: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: color 0.3s;
}

.footer-section li:hover {
  color: #fff;
}

.contact-info p {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.contact-info i {
  margin-right: 10px;
}

.social-icons {
  display: flex;
  margin-top: 10px;
}

.social-icons i {
  font-size: 20px;
  margin-right: 15px;
  cursor: pointer;
  transition: color 0.3s;
}

.social-icons i:hover {
  color: #fff;
}

.copyright {
  background-color: #1c272b;
  padding: 15px 0;
  text-align: center;
  font-size: 12px;
  width: 100%;
}

.section-block {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  width: 100%;
  box-sizing: border-box;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .footer-section {
    min-width: 150px;
  }
}

@media (max-width: 992px) {
  .header-content {
    padding: 0 3vw;
  }
  
  .nav-content {
    padding: 0 3vw;
  }
  
  .mall-content {
    padding: 20px 3vw;
  }
  
  .footer-content {
    padding: 0 3vw 40px;
  }
}

@media (max-width: 768px) {
  .header-content {
    flex-wrap: wrap;
    padding: 0 15px;
  }
  
  .logo-area {
    width: 100%;
    text-align: center;
    margin-bottom: 10px;
  }
  
  .search-box {
    width: 100%;
    order: 3;
    margin: 10px 0 0 0;
  }
  
  .user-actions {
    margin-left: auto;
  }
  
  .nav-content {
    padding: 0 15px;
    overflow-x: auto;
  }
  
  .category-menu-list {
    flex-wrap: nowrap;
    overflow-x: auto;
  }
  
  .mall-content {
    padding: 15px;
  }
  
  .footer-content {
    padding: 0 15px 30px;
  }
  
  .footer-section {
    width: 100%;
    padding: 0;
  }
}
</style> 